package com.ctparking;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Prenotation extends Activity{
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	    	startActivity(new Intent(Prenotation.this, Main.class));
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
private static class EfficientAdapter extends BaseAdapter {
    	
        private LayoutInflater mInflater;
        public Context ctxt;
        public Activity act;

        public EfficientAdapter(Context context, Activity activity) {
            mInflater = LayoutInflater.from(context);           
            ctxt = context;
            act = activity;           
        }
        
        public int getCount() {
            return prenotation_list.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView, final ViewGroup parent) {
            final ViewHolder holder;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.prenotazioni_list_riga, null);

                holder = new ViewHolder();
                
                holder.data = (TextView) convertView.findViewById(R.id.txt_Data);
                holder.ora = (TextView) convertView.findViewById(R.id.txt_Ora);
                holder.codice = (TextView) convertView.findViewById(R.id.txt_Codice);
                holder.bt_rem = (Button) convertView.findViewById(R.id.btnEliminaPrenotazione);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final Prenotazione p = prenotation_list.get(position);
            
            holder.data.setText(p.data);
            holder.ora.setText(p.ora);
            holder.codice.setText(p.codice);
            
            holder.bt_rem.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
					builder.setMessage("Sei sicuro di voler eliminare la prenotazione " + p.codice + "?");
					builder.setCancelable(false);
					builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {}});
					builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							
							String[] s = p.codice.split("_");
							String nomeParcheggio = s[0]+"_"+s[1];
							String annullaPrenotazione = "-1" ;
							boolean continua = true;
							int i = 0;
							while(i < Database.parkingList.size() && continua){
								 if(Database.parkingList.get(i).getNomeWeb().equals(nomeParcheggio)){
									 continua = false;
									 annullaPrenotazione = Database.parkingList.get(i).incPosti(Database.ConnectionString + "annulla/" + p.codice);
								 }
								 i++;
							}
							
							 //AGGIORNO IL FILE Prenotazioni.txt
							if(annullaPrenotazione != "-1"){
								try{
									ArrayList<String> array_str = new ArrayList<String>();
									FileInputStream fis = ctxt.openFileInput("Prenotazioni.txt");
									InputStreamReader isr = new InputStreamReader(fis);
									BufferedReader br = new BufferedReader(isr); 
									prenotation_list.clear();
									String riga = null;
									while((riga = br.readLine()) != null){
										s = riga.split(";");
										if(!s[5].equals(p.codice)){
											array_str.add(riga);
										}
									}
									br.close();
									ctxt.deleteFile("Prenotazioni.txt");
									int size = array_str.size();
									if(size > 0){
										FileOutputStream fos = ctxt.openFileOutput("Prenotazioni.txt", Context.MODE_PRIVATE|Context.MODE_APPEND);
										OutputStreamWriter osw = new OutputStreamWriter(fos);
										BufferedWriter bw = new BufferedWriter(osw);
										for(int j = 0; j < size; j++ )
											bw.write(array_str.get(j)+"\n");
										bw.flush();
										bw.close();
									}
									else{
										FileOutputStream fos = ctxt.openFileOutput("Prenotazioni.txt", Context.MODE_PRIVATE|Context.MODE_APPEND);
										fos.close();
									}
									
								}catch(FileNotFoundException e){
									e.printStackTrace();
								}catch(IOException e){
									e.printStackTrace();
								}
							}
							if (annullaPrenotazione.equals("-1")) annullaPrenotazione = "Errore di connessione con il server...Riprovare";
							else{
								if (annullaPrenotazione.equals("-2")) annullaPrenotazione = "Prenotazione non valida o scaduta, nessuna corrispondenza sul server. Eliminata dal file locale";
							}
								
							Toast.makeText(ctxt,annullaPrenotazione,Toast.LENGTH_LONG).show();
							act.startActivity(new Intent(act , Prenotation.class));
							
					    }
					});
					builder.show();
				}
			});

            return convertView;
        }

        static class ViewHolder {
            TextView data;
            TextView ora;
            TextView codice;
            Button bt_rem;
        }
    }

	static ArrayList<Prenotazione> prenotation_list = new ArrayList<Prenotazione>();
	ListView lv;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int orientation=getResources().getConfiguration().orientation;
    	if (orientation == 1) {
            // Portrait
    		setContentView(R.layout.prenotazioni);
        }
        else if (orientation == 2) {
            // Landscape
        	setContentView(R.layout.landscape_prenotazioni);
        }            
    
        

        Context c = this.getApplicationContext();
		try{
			
			FileInputStream fis = c.openFileInput("Prenotazioni.txt");
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr); 
			prenotation_list.clear();
			String riga = null;
			String[] s;
			while((riga = br.readLine()) != null){
				s = riga.split(";");
				Prenotazione p = new Prenotazione(s[1],s[3],s[5]);
				prenotation_list.add(p);
			}
			
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		
		if (prenotation_list.size() == 0)
			Toast.makeText(this, "Non risultano prenotazioni a tuo carico", Toast.LENGTH_LONG).show(); 
		
		lv = (ListView)findViewById(R.id.list_Prenotazioni);
        lv.setAdapter(new EfficientAdapter(this,this));
        
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            	
            }
        });
	}
}
